// =============================================================
// master-worker model using Coord
// ---------------------------------------
// Author : Woo-Hyun Kim
// Email : woorung@icu.ac.kr or woorung@nhncorp.com
// Date : Oct. 29, 2008
// =============================================================
#include <iostream>

#include "discovery/Coord.h"

int perform_task(pair<string,string> &mytask)
{
	mytask.first = mytask.second;

	FILE *p = popen(mytask.second.c_str(),"r");
	if(!p) cerr << "pipe open error" << endl;
	else {
		char buf[1024];
		stringstream ss;
		while(fgets(buf, 1023, p)!=0) {
			ss << buf;
			memset((char *)buf, '\0', sizeof(buf));
		}

		mytask.second = ss.str();
	}
	pclose(p);
}

int main(int argc, char **argv)
{
	vector<string> tasks;

	tasks.push_back("hostname");
	tasks.push_back("date");
	tasks.push_back("ps -ef");
	tasks.push_back("who");
	tasks.push_back("echo coord");

	vector<pid_t> pid;

	for(int i=0;i<tasks.size();i++) {
		pid.push_back(fork());

		if(pid[i]==0) { // workers
			Coord worker("worker.market");
			worker.autoclean(false);

			pair<string,string> mytask;
			mytask.first = "job";

			worker.take(mytask);

			perform_task(mytask);

			worker.write(mytask);

			exit(1);
		}
	}

	// master 
	Coord master("worker.market");
	master.autoclean(false);

	pair<string,string> task;
	task.first = "job";

	for(int i=0;i<tasks.size();i++) {
		task.second = tasks[i];
		master.write(task);
	}

	for(int i=0;i<tasks.size();i++) {
		pair<string,string> report;
		report.first = tasks[i];
		master.take(report);

		cout << "task = " << report.first << endl;
		cout << "-----------------------------" << endl;
		cout << report.second << endl;
		cout << endl;
		cout << endl;
	}

        return 1;
}
